#!/usr/bin/make -f
export DH_VERBOSE = 1

# Use DEB_BUILD_OPTIONS's parallel=n option (see Policy 4.9.1)
ifneq (,$(findstring parallel,$(DEB_BUILD_OPTIONS)))
PARALLEL_JOBS := $(shell echo $(DEB_BUILD_OPTIONS) | \
	sed -e 's/.*parallel=\([0-9]\+\).*/\1/')
else
PARALLEL_JOBS := 1
endif

ifeq (amd64,$(DEB_HOST_ARCH_CPU))
BUILD_TYPE += ReleaseX64
BUILD_FLAGS += --arch=x64
LIBS_DIR := $(CURDIR)/dart/buildtools/sysroot/linux/lib/x86_64-linux-gnu
else
ifeq (i386,$(DEB_HOST_ARCH_CPU))
BUILD_TYPE += ReleaseIA32
BUILD_FLAGS += --arch=ia32
LIBS_DIR := $(CURDIR)/dart/buildtools/sysroot/linux/lib/i386-linux-gnu
else
ifeq (arm,$(DEB_HOST_ARCH_CPU))
ifeq ($(DEB_BUILD_ARCH_CPU),$(DEB_HOST_ARCH_CPU))
BUILD_TYPE += ReleaseARM
else
BUILD_TYPE += ReleaseXARM
endif
BUILD_FLAGS += --arch=arm
LIBS_DIR := $(CURDIR)/dart/buildtools/sysroot/linux/lib/arm-linux-gnueabihf
else
ifeq (arm64,$(DEB_HOST_ARCH_CPU))
ifeq ($(DEB_BUILD_ARCH_CPU),$(DEB_HOST_ARCH_CPU))
BUILD_TYPE += ReleaseARM64
else
BUILD_TYPE += ReleaseXARM64
endif
BUILD_FLAGS += --arch=arm64
LIBS_DIR := $(CURDIR)/dart/buildtools/sysroot/linux/lib/aarch64-linux-gnu
else
ifeq (riscv64,$(DEB_HOST_ARCH_CPU))
ifeq ($(DEB_BUILD_ARCH_CPU),$(DEB_HOST_ARCH_CPU))
BUILD_TYPE += ReleaseRISCV64
else
BUILD_TYPE += ReleaseXRISCV64
endif
BUILD_FLAGS += --arch=riscv64
LIBS_DIR := $(CURDIR)/dart/buildtools/sysroot/focal/lib/riscv64-linux-gnu
else
$(error unsupported target arch '$(DEB_HOST_ARCH_CPU)')
endif
endif
endif
endif
endif

# Verbose?
ifeq (1,$(DH_VERBOSE))
BUILD_FLAGS += --verbose
endif

%:
	dh $@

override_dh_auto_clean:
	echo $(DEB_BUILD_OPTIONS)
	rm -fr dart/out dart/Makefile
	find . -name *.tmp -execdir rm -f {} \;
	find . -name *.pyc -execdir rm -f {} \;
	find . -name *.mk -execdir rm -f {} \;
	find . -name *.Makefile -execdir rm -f {} \;

override_dh_auto_configure:
	python3 dart/tools/generate_buildfiles.py

override_dh_auto_build:
	cd dart; \
	python3 tools/build.py --mode release \
	  $(BUILD_FLAGS) $(TOOLCHAIN) create_sdk; \
	cd ..

# Building the Dart SDK will already strip all binaries.
override_dh_strip:

# This override allows us to ignore spurious missing library errors when
# cross-compiling.
override_dh_shlibdeps:
	dh_shlibdeps --dpkg-shlibdeps-params=--ignore-missing-info -l $(LIBS_DIR)

override_dh_auto_install:
	mkdir -p debian/tmp/out
	cp -R dart/out/$(BUILD_TYPE)/dart-sdk debian/tmp/out
	mv debian/tmp/out/dart-sdk debian/tmp/out/dart
	dh_install
	dh_link
